import {DatePipe} from '@angular/common';
import {Component, OnInit} from '@angular/core';
import {Router} from '@angular/router';
import {__assign} from 'tslib';
import {environment} from '../../../environments/environment';
import {CommonHttp} from '../../common/common.http';
import {CommonTool} from '../../common/common.tool';
import {LoginDto} from '../base.model';
import {BaseService} from '../base.service';
import {NzMessageService} from 'ng-zorro-antd';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.scss'],
  providers: [DatePipe]
})
export class LoginComponent implements OnInit {
  constructor(public datePipe: DatePipe,
              public baseService: BaseService,
              private message: NzMessageService,
              private router: Router) {
  }

  ngOnInit(): void {
    const param = CommonTool.getUrlParam(location.href);
    if (param['code']) {
      const state = localStorage.getItem('state');
      if (param['state'] === state) {
        this.baseService.getToken(param['code']).subscribe(res => {
          this.init(res);
        });
      } else {
        this.message.error('state错误！');
      }
    } else {
      const state = Math.ceil(Math.random() * 100000);
      const redirectUri = escape(location.origin + '/#/login');
      location.href = environment.config.loginUrl + '&redirectUri=' + redirectUri + '&state=' + state;
      localStorage.setItem('state', state + '');
    }
  }

  /**
   * 提交
   */
  public init(res): void {
    if (!environment.openBackEnd) {
      const loginDto = new LoginDto();
      loginDto.accessToken = '123456';
      loginDto.validTime = 1800000;
      loginDto.updateTime = this.datePipe.transform(new Date(), 'yyyy-MM-dd HH:mm:ss');
      CommonTool.setCookie(environment.tokenKey, JSON.stringify(loginDto));
      this.router.navigate(['/home']);
      const commonHttp = new CommonHttp();
      const menus = JSON.parse(commonHttp.get('/assets/json/menu.json').data);
      const authorityList = JSON.parse(commonHttp.get('/assets/json/authority.json').data);
      const authorityCode = [];
      for (const authority of authorityList) {
        authorityCode.push(authority.code);
      }
      const menuList = this.baseService.menuHandle(menus, authorityCode);
      if (menuList) {
        sessionStorage.setItem(environment.menuKey, JSON.stringify(menuList));
      }
      return;
    }
    const authorityCodes = res['authorityCodes'];
    CommonTool.setCookie(environment.tokenKey, JSON.stringify(new LoginDto(res)));
    // 获取菜单
    this.baseService.getSystemMenuList().subscribe(menus => {
      const menuList = this.baseService.menuHandle(menus, authorityCodes);
      if (menuList) {
        sessionStorage.setItem(environment.menuKey, JSON.stringify(menuList));
        this.router.navigate(['/home']);
      }
    });
  }
}
